package com.zwj.controller;

import com.zwj.entity.Conversation;
import com.zwj.service.ConversationService;
import com.zwj.service.MessageService;
import com.zwj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/im_api/addFriends/{username}")
@Component
@Controller
@Slf4j
public class AddFriendsController {


    private static ConversationService conversationService;

    @Resource
    public void setConversationService(ConversationService conversationService) {
        AddFriendsController.conversationService = conversationService;
    }


    /**
     * 全部在线会话  PS: 基于场景考虑 这里使用线程安全的Map存储会话对象。
     * 以用户姓名为key
     */
    private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();

    /**
     * 当通信发生异常：打印错误日志
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 当客户端打开连接：1.添加会话对象 2.更新在线人数
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        log.info("{} 用户连接",username + "add");
        onlineSessions.put(username, session);

    }

    /**
     * 当客户端发送消息：1.获取它的用户名和消息 2.发送消息给所有人
     * <p>
     * PS: 这里约定传递的消息为JSON字符串 方便传递更多参数！
     */
    @OnMessage
    public void onMessage(Session session, String friendUsername) throws IOException {

        Set<String> strings = onlineSessions.keySet();
        String username = "";
        for (String string : strings) {
            if(onlineSessions.get(string) == session) {
                username = string;
            }
        }
        conversationService.save(new Conversation(username,friendUsername));
        onlineSessions.get(friendUsername).getBasicRemote().
                sendText(username);


    }

    /**
     * 当关闭连接：1.移除会话对象 2.更新在线人数
     */
    @OnClose
    public void onClose(Session session, @PathParam("username") String username) {
        log.info("{} 用户关闭",username + "add");
        onlineSessions.remove(username);
    }

    /**
     * 公共方法：发送信息给所有人
     */
    private static void sendMessageToAll(String msg) {
        onlineSessions.forEach((id, session) -> {
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 单独聊天方法：发送信息给指定的人
     */
    private static void sendMessageToUser(String msg) {

    }

}
